from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info import constants
from info.commom import user_login_data
from info.models import User, News
from info.utils.response_code import RET
from . import index_blu
from info import redis_store

@index_blu.route('/news_list')
def news_list():
    """
    获取首页新闻数据
    :return:
    """
    # 1.获取参数
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')

    # 2.教研参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    filters = []
    if cid != 1:  # 查询的不是最新的数据
        # 需要添加条件
        filters.append(News.category_id == cid)
    # 查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as f:
        current_app.logger.error(f)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')
    # 取到当前页的数据
    news_model_list = paginate.items  # 模型对象列表
    total_page = paginate.pages
    current_page = paginate.page
    # 将模型对象列表转成字典对象列表
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())
    data = {
        'total_page': total_page,
        'current_page': current_page,
        'news_dict_li': news_dict_li
    }
    return jsonify(errno=RET.OK, errmsg='ok', data=data)

@index_blu.route('/')
@user_login_data
def index():
    """
    显示主页面逻辑
    １．如果用户已经登录，将用户的信息传到模板中，供页面显示
    :return:
    """
    # 查询用户登录信息
    user = g.user

    # 右侧新闻排行逻辑
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as f:
        current_app.logger.error(f)
    # 定义一个空的字典列表。里面装的时字典
    news_dict_li = []
    # 遍历对象的列表，把对象的字典添加到字典列表中
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())
    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li

    }
    return render_template('news/index.html', data=data)

# 在打开网站的时候，浏览器会默认请求跟路径+favicon.ico来作为网站页面小图标
# send_static_file是flask指定访问静态文件时调用的方法
@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')
